package demo4.mapper;

import com.alibaba.druid.pool.DruidDataSource;
import demo4.config.DBUtil;
import demo4.vo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@Component
public class UserMapper implements IUserMapper{
    @Autowired
    private DruidDataSource dataSource;
    @Override
    public int insert(User user){
        try (Connection connection = dataSource.getConnection();){
            String sql = "INSERT INTO user(username,password,nickname,age) " +
                    "VALUES(?,?,?,?)";
            PreparedStatement ps = connection.prepareStatement(sql);
            ps.setString(1, user.getUsername());
            ps.setString(2, user.getPassword());
            ps.setString(3, user.getNickname());
            ps.setInt(4, user.getAge());
            return ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }
    @Override
    public User selectByUsername(String username){

        try(Connection connection = dataSource.getConnection();) {
            String sql = "INSERT INTO user(username,password,nickname,age) VALUES (?,?,?,?);";
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1,username);
            ResultSet resultSet = preparedStatement.executeQuery();
            if(resultSet.next()){
                User user = new User();
                user.setId(resultSet.getInt("id"));
                user.setUsername(resultSet.getString("username"));
                user.setNickname(resultSet.getString("nickname"));
                user.setPassword(resultSet.getString("password"));
                user.setAge(resultSet.getInt("age"));
                return user;
            }

        } catch (SQLException e){
            e.printStackTrace();
        }
        System.out.println("查询用户信息");
        return null;
    }
}
